import cgi
import os
import xml.etree.cElementTree as etree
import logging
import datetime

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

# Third party imports
import appjson
import oauth    
from Crypto.PublicKey import RSA
from Crypto.Util import number
#fb import

import prodHandler
import registration
from db_model import Product, User, Envy
logging.getLogger().setLevel(logging.DEBUG)

_BestBuyRemixKey = 'umbf58y7qutc8r3vmv9j2qj2'

class MainPage(webapp.RequestHandler):
  def get(self):
    results={}
    products = []
    errors = []

    ## check for a search request
    if self.request.path.startswith('/product'):
      ## get the product to search for 
      ## from the submit form
      #http://prodenvy.appspot.com/product/?uid=16774158048318259517&brand=Apple&model=MB533LLA&siteSku=8772081&siteName=BestBuy

      ## show: filter that specifies exact attributes to return.
      ## remove if you want everything
      f = '&show=sku,productId,name,artistName,type,regularPrice,salePrice,url,thumbnailImage,inStoreAvailability,onlineAvailability'

      ## Replace with whatever you want.
      ## Note the wildcard '*'. It lets you search on
      url = 'http://api.remix.bestbuy.com/v1/products/'+self.request.get('siteSku')+'.json?&apiKey=' + _BestBuyRemixKey;
      logging.debug(url)

      result = urlfetch.fetch(url)
      ##url = 'http://api.remix.bestbuy.com/v1/products(' + search + ')?&apiKey=' + _BestBuyRemixKey;

      if result.status_code == 200:
        item=appjson.read(result.content)
        if item:
          product = Product()
          product.name = item['name']
          product.siteSku = str(item['sku'])
          product.type = item['type']
          product.url = item['url']
          product.imageurl = item['thumbnailImage']
          product.latestPrice = str(item['salePrice'])
          product.latestPriceDate = datetime.datetime.now()
          product.siteName = self.request.get('siteName')
          product.model = self.request.get('model')
          product.brand = self.request.get('brand')
          product.put()

          user = db.Query(User).filter('orkutId =', self.request.get('uid')).get()
          if not user:
            user = User()
            user.orkutId = self.request.get('uid')
            user.put()
            
          envyobj = Envy()
          envyobj.user = user.key()
          envyobj.product = product.key()
          envyobj.envy = 'Love it'
          envyobj.createdDate = datetime.datetime.now()
          envyobj.updatedDate = datetime.datetime.now()
          envyobj.owningStatus = self.request.get('status')
          envyobj.put()

      else:
        er = {'desc': '%s' % result.status_code,}
        errors.append(er)

      self.redirect('http://www.orkut.com/Main#Application.aspx?appId=746091680518')
    else:
      self.redirect('http://www.orkut.com/Main#Application.aspx?appId=746091680518')

       
    
application = webapp.WSGIApplication(
                                     [#('/', MainPage),
                                      ('/product', MainPage)
                                      ,('/seed', prodHandler.Seed)
                                      ,('/register', registration.UserServer)
                                      ,('/activity', prodHandler.ActivityServer) #me and my friends envy list
                                      ,('/updates', prodHandler.UpdateServer)
                                      ,('/envy', prodHandler.EnvyServer)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
